import {
  Injectable,
  CanActivate,
  ExecutionContext,
  HttpException,
} from '@nestjs/common';
import { Observable } from 'rxjs';
import { createHash } from 'crypto';

const validateRequest = (request) => {
  const headers = request.headers;
  const random = headers.random;
  const timestamp = headers.timestamp;
  const sign = headers.sign;
  const app_id = 'jasenahut1234567890~~$%';
  const sign2 = createHash('md5')
    .update(`${app_id}${timestamp}${random}`)
    .digest('hex');
  if (sign !== sign2) {
    throw new HttpException('验签已失效', 500);
  }
  return sign === sign2;
};
@Injectable()
export class CommonGuard implements CanActivate {
  canActivate(
    context: ExecutionContext,
  ): boolean | Promise<boolean> | Observable<boolean> {
    const request = context.switchToHttp().getRequest();
    return validateRequest(request);
  }
}
